/**
 * SaveImageFileChooser.java
 * 
 * @date: 2012-03-15
 * @author: Xiaoyu Guo (MUN# 200982155)
 * This file is part of the course project for COMP 6752, 
 * Application of Computer Graphics. All the file is written
 * by myself.
 */
package mun.cs6752.project.ui.fileChooser;

import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;


/** An improved file chooser for saving the images
 * @author Xiaoyu Guo
 */
public class SaveImageFileChooser extends JFileChooser {
    private static final long serialVersionUID = -5440636954243992490L;
    
    /**
     * Constructor
     */
    public SaveImageFileChooser(){
        setMultiSelectionEnabled(false);
        setFileSelectionMode(JFileChooser.FILES_ONLY);
        for(FileFilter f : ImageFileFilter.FILE_FILTERS){
            addChoosableFileFilter(f);
        }
    }
    
    /* (non-Javadoc)
     * @see javax.swing.JFileChooser#getSelectedFile()
     */
    @Override
    public File getSelectedFile() {
        File selectedFile = super.getSelectedFile();

        if (selectedFile != null) {
            try{
                String name = selectedFile.getName();
                FileNameExtensionFilter selectedFilter = (FileNameExtensionFilter) this.getFileFilter();
                String selectedExt = selectedFilter.getExtensions()[0];
                if (!name.endsWith('.' + selectedExt)){
                    selectedFile = new File(
                        selectedFile.getParentFile(), name + '.' + selectedExt
                    );
                }
            }catch(Exception ex){
                
            }
        }

        return selectedFile;
    }
    
    /* (non-Javadoc)
     * @see javax.swing.JFileChooser#approveSelection()
     */
    @Override 
    public void approveSelection() {
        if (getDialogType() == SAVE_DIALOG) {
            File selectedFile = getSelectedFile();
            if ((selectedFile != null) && selectedFile.exists()) {
                int response = JOptionPane.showConfirmDialog(
                    this,
                    "The file " + selectedFile.getName() + 
                    " already exists. Do you want to replace the existing file?",
                    "Ovewrite file", 
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE
                );
                if (response != JOptionPane.YES_OPTION){
                    return;
                }
            }
        }

        super.approveSelection();
    }
}
